package com.hmdp.interceptor;


import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.utils.JwtUtil;
import com.hmdp.utils.UserHolder;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("authorization");
        //解析token
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String userName = claims.get("userName", String.class);
        //保存用户信息
        UserDTO userDTO = new UserDTO();
        userDTO.setId(userId);
        userDTO.setNickName(userName);
        UserHolder.saveUser(userDTO);
        System.err.println("我是拦截器,拦截用户"+userDTO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
